import React, { ReactElement, useState, useEffect } from 'react'
import style from './index.module.less'
import Search, { formatCondition } from './components/search'
import Table from '@components/table'
import { ConditionSchema } from '@src/components/schema/condition'
import { CaseSchema } from '@src/components/schema/caseSchema'
import { getColumn } from './util'
import { awaitWrap } from '@src/assets/js/tool'
import { getCaseListRequest, addCaseRequest, getSeriesRequest } from './ajax'
import { Space, Button, message, Modal } from 'antd'
import SeriesModal from './components/seriesModal'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { SeriesSchema } from '@src/components/schema/seriesCase'
import { Dispatch } from 'redux'
import { addWindow, delWindow } from '@src/redux/actions/tab'
import { useDispatch } from 'react-redux';

const { confirm } = Modal

// 初始化数据
async function initSeriesData (seriesid: string, setSeriesData: (v: SeriesSchema) => void): Promise<void> {
  const [e, d] = await awaitWrap(getSeriesRequest(seriesid))
  if (e === null && d !== null) {
    setSeriesData(d)
  }
}

// 初始化数据
async function initData (data: { [k: string]: any}, setDataSource: (v: CaseSchema[]) => void, setTotal: (v: number) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getCaseListRequest({
    condition: formatAllCondition(data),
    page: data.page,
    limit: data.limit
  }))
  setLoading(false)
  if (e === null && d !== null) {
    setTotal(d.total)
    setDataSource(d.list)
  }
}

// 格式化搜索条件
function formatAllCondition (o: { [k: string]: any }): ConditionSchema[] {
  const condition = formatCondition(o)
  if (typeof o.status === 'string') {
    condition.push({ k: 'score_status', o: '=', v: o.status })
  }
  return condition
}

// 显示系列案详情输入框
function createHandle (keys: React.Key[], setVisible: (v: boolean) => void): void {
  if (keys.length === 0) {
    message.warning('请选择系列案案件').then(null, null)
    return undefined
  }
  setVisible(true)
}

// 二次确认添加
function confirmAdd (id: string, keys: React.Key[], seriesData: SeriesSchema, dispatch: Dispatch): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确定要添加这些案件？',
    onOk: () => {
      addHandle(id, keys, seriesData, dispatch).catch(e => console.error(e))
    }
  })
}

// 添加案件
async function addHandle (id: string, keys: React.Key[], seriesData: SeriesSchema, dispatch: Dispatch): Promise<void> {
  const hide = message.loading('提交中', 120)
  const [e] = await awaitWrap(addCaseRequest(id, keys))
  hide()
  if (e === null) {
    message.success('添加成功').then(null, null)
    dispatch(delWindow(`series-case-input-${seriesData.id}`))
    dispatch(addWindow({
      id: `series-case-list-${id}`,
      title: seriesData.serieno,
      componentName: 'SeriesCaseList',
      forceRefresh: true,
      meta: {
        id
      }
    }))
  }
}

interface Props {
  meta: {
    id: string
  }
}

function Main ({ meta }: Props): ReactElement {
  const dispatch = useDispatch()
  const [visible, setVisible] = useState(false)
  const [dataSource, setDataSource] = useState<CaseSchema[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [seriesData, setSeriesData] = useState<SeriesSchema | null>(null)
  const [params, setParams] = useState<{[k: string]: any}>({})
  useEffect(() => {
    if (typeof meta.id === 'string') {
      initSeriesData(meta.id, setSeriesData).catch(e => console.error(e))
    }
  }, [meta])
  return (
    <div className={style.container}>
      <SeriesModal keys={selectedRowKeys} visible={visible} seriesData={seriesData as SeriesSchema} hide={() => setVisible(false)} />
      <div className={style.search}>
        <Search params={params} setParams={setParams} />
      </div>
      <div className={style.table}>
        <div className={style['operate-line']}>
          <span className={style['operate-title']}>案件列表</span>
        </div>
        <Table params={params} setParams={setParams} columns={getColumn()} loading={loading} total={total} dataSource={dataSource} selectable selectedRowKeys={selectedRowKeys} setSelectedRowKeys={setSelectedRowKeys} onChange={async d => await initData(d, setDataSource, setTotal, setLoading)} />
      </div>
      <div className={style['btn-line']}>
        <span className={style['total-message']}>
          <span>已选择</span>
          <span className={style['total-num']}>{selectedRowKeys.length}</span>
          <span>项</span>
        </span>
        <Space>
          {
            typeof meta.id === 'string'
              ? (
              <Button type='primary' onClick={() => confirmAdd(meta.id, selectedRowKeys, seriesData as SeriesSchema, dispatch)}>确定添加</Button>
                )
              : (
              <Button type='primary' onClick={() => createHandle(selectedRowKeys, setVisible)}>创建系列案</Button>
                )
          }
        </Space>
      </div>
    </div>
  )
}

export default Main
